package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private ClazzService clazzService;
    @Override
    public PageResult getPageResult(StudentQueryParam student) {
        Page page = new Page<>(student.getPage(),student.getPageSize());
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(student.getName()!=null&&student.getName()!="",Student::getName,student.getName())
                .eq(student.getDegree()!=null,Student::getDegree,student.getDegree())
                .eq(student.getClazzId()!=null,Student::getClazzId,student.getClazzId());

        page = page(page,wrapper);




        List<Student> stus = page.getRecords();
        List<Long> clazzids = stus.stream().map(stu -> stu.getClazzId()).collect(Collectors.toList());
        if(!clazzids.isEmpty()){
            List<Clazz> clazzes = clazzService.listByIds(clazzids);

            stus.forEach(stu->{
                clazzes.forEach(clazz->{
                    if(stu.getClazzId()!=null && clazz.getId().equals(stu.getClazzId())){
                        stu.setClazzName(clazz.getName());
                    }
                });
            });
        }

        return new PageResult<>(page.getTotal(), stus);
    }

    @Override
    public void updateScoreById(Integer id, Integer score) {
        LambdaUpdateWrapper<Student> wrapper  = new LambdaUpdateWrapper<>();

        wrapper.eq(Student::getId,id)
                .setSql("violation_score = violation_score + " + score + " , violation_count = violation_count + 1");
        update(wrapper);
    }
}
